package com.sinping.qh.api.admin.lab;

import com.sinping.qh.api.support.*;
import com.sinping.qh.dto.admin.lab.LabImportExcelDto;
import com.sinping.qh.dto.admin.lab.LaboratoryDto;
import com.sinping.qh.service.admin.ILaboratoryService;
import com.sinping.qh.utils.mapper.JsonMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;

/**
 * @author jiahuaiqing
 * @create 2018/6/1
 */
@Api(value = "admin实验室管理", description = "admin实验室管理")
@RestController
@RequestMapping(name = "admin实验室管理", value = Const.ADMIN_URI + "laboratory")
@Slf4j
public class LaboratoryEndPoint {

    @Autowired
    ILaboratoryService iLaboratoryService;

    @ApiOperation(httpMethod = "POST", value = "新增实验室", consumes = MediaTypes.JSON)
    @RequestMapping(method = RequestMethod.POST, name = "新增实验室")
    public ResDto addLaboratory(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"lab_name\":\"xxxxxx\",\"unit_id\":\"xxxxxx\",\"building_id\":\"xxxxxx\",<Br>\"unit_name\":\"xxxxxx\",\"building_name\":\"xxxxxx\",<Br>\"offices\":\"xxxxxx\",\"room_no\":\"xxxxxx\",\"risk_manager\":\"xxxxxx\",<Br>\"risk_level\":\"xxxxxx\",\"room_area\":\"xxxxxx\",\"telephone\":\"xxxxxx\"}")
    @RequestParam(required = true) String msg) {

        try {
            LaboratoryDto laboratoryDto = JsonMapper.defaultMapper().fromJson(msg, LaboratoryDto.class);
            if (laboratoryDto == null) {
                log.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
//            if (!StringUtils.isNotBlank(laboratoryDto.getLabName())) {
//                return new ResDto(Const.PARAM_ERROR, "实验室名称不为空");
//            }
            if (!StringUtils.isNotBlank(laboratoryDto.getBuildingId())) {
                return new ResDto(Const.PARAM_ERROR, "楼宇id不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getUnitId())) {
                return new ResDto(Const.PARAM_ERROR, "院系id不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getBuildingName())) {
                return new ResDto(Const.PARAM_ERROR, "楼宇不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getUnitName())) {
                return new ResDto(Const.PARAM_ERROR, "院系不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getRoomNo())) {
                return new ResDto(Const.PARAM_ERROR, "房间号不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getRoomArea())) {
                return new ResDto(Const.PARAM_ERROR, "房间面积不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getRiskLevel())) {
                return new ResDto(Const.PARAM_ERROR, "危险级别不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getRiskManager())) {
                return new ResDto(Const.PARAM_ERROR, "安全管理人不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getTelephone())) {
                return new ResDto(Const.PARAM_ERROR, "联系电话不为空");
            }

            ResDto resDto = iLaboratoryService.addLaboratory(request, laboratoryDto);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.FORMAT_ERROR, "数据解析异常");
        }
    }

    @ApiOperation(httpMethod = "PUT", value = "修改实验室信息", consumes = MediaTypes.JSON)
    @RequestMapping(method = RequestMethod.PUT, name = "修改实验室信息")
    public ResDto updateLaboratory(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"id\":\"xxxxxx\",\"lab_name\":\"xxxxxx\",\"unit_id\":\"xxxxxx\",<Br>\"building_id\":\"xxxxxx\",\"unit_name\":\"xxxxxx\",\"building_name\":\"xxxxxx\",<Br>\"offices\":\"xxxxxx\",\"room_no\":\"xxxxxx\",\"risk_manager\":\"xxxxxx\",<Br>\"risk_level\":\"xxxxxx\",\"room_area\":\"xxxxxx\",\"telephone\":\"xxxxxx\"}")
    @RequestParam(required = true) String msg) {

        try {
            LaboratoryDto laboratoryDto = JsonMapper.defaultMapper().fromJson(msg, LaboratoryDto.class);
            if (laboratoryDto == null) {
                log.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getId())) {
                return new ResDto(Const.PARAM_ERROR, "id不为空");
            }
//            if (!StringUtils.isNotBlank(laboratoryDto.getLabName())) {
//                return new ResDto(Const.PARAM_ERROR, "实验室名称不为空");
//            }
            if (!StringUtils.isNotBlank(laboratoryDto.getBuildingId())) {
                return new ResDto(Const.PARAM_ERROR, "楼宇id不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getUnitId())) {
                return new ResDto(Const.PARAM_ERROR, "院系id不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getBuildingName())) {
                return new ResDto(Const.PARAM_ERROR, "楼宇不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getUnitName())) {
                return new ResDto(Const.PARAM_ERROR, "院系不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getRoomNo())) {
                return new ResDto(Const.PARAM_ERROR, "房间号不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getRoomArea())) {
                return new ResDto(Const.PARAM_ERROR, "房间面积不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getRiskLevel())) {
                return new ResDto(Const.PARAM_ERROR, "危险级别不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getRiskManager())) {
                return new ResDto(Const.PARAM_ERROR, "安全管理人不为空");
            }
            if (!StringUtils.isNotBlank(laboratoryDto.getTelephone())) {
                return new ResDto(Const.PARAM_ERROR, "联系电话不为空");
            }

            ResDto resDto = iLaboratoryService.updateLaboratory(request, laboratoryDto);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            ResDto resDto = new ResDto();
            resDto.setStatus(Const.FORMAT_ERROR);
            resDto.setMsg("数据解析异常");
            return resDto;

        }
    }

    @ApiOperation(httpMethod = "GET", value = "获取实验室详情", consumes = MediaTypes.JSON)
    @RequestMapping(method = RequestMethod.GET, name = "获取实验室详情", value = "/{id}")
    public ResDto getLaboratoryById(@ApiParam(name = "id", value = "id:5b0e7a300a4145204c48768c") @PathVariable String id) {

        try {
            if (!StringUtils.isNotBlank(id)) {
                return new ResDto(Const.PARAM_ERROR, "实验室id不为空");
            }
            ResDto resDto = iLaboratoryService.getLaboratoryById(id);
            return resDto;
        } catch (Exception e) {
            ResDto resDto = new ResDto();
            e.printStackTrace();
            resDto.setStatus(Const.FORMAT_ERROR);
            resDto.setMsg("数据解析异常");
            return resDto;
        }
    }

    /**
     * 获取分页列表
     */
    @ApiOperation(httpMethod = "GET", value = "获取实验室分页列表", consumes = MediaTypes.JSON,notes = "condition:{lab_name: \"\", unit_id: \"\", building_id: \"\", status: 0} 条件传以上参数,status是必须传的")
    @RequestMapping(value = "/list", name = "获取实验室分页列表", method = RequestMethod.GET)
    public ResDto getLaboratoryFrontPage(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"page_size\":10, \"page_current\":1, \"order_by\":null, \"condition\":{<Br>\"status\" : \"0\"}}")
    @RequestParam(required = true) String msg) {
        try {
            FrontPage frontPage = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
            if (frontPage == null) {
                log.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            ResDto reDto = iLaboratoryService.getLaboratoryFrontPage(request, frontPage);
            return reDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.FORMAT_ERROR, "Json数据解析异常");
        }

    }

    @Deprecated
    @ApiOperation(httpMethod = "DELETE", value = "删除实验室信息", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/{id}", name = "删除实验室信息", method = RequestMethod.DELETE)
    public ResDto deleteLaboratoryById(HttpServletRequest request, @ApiParam(name = "id", value = "54f8c268f02c4ebf9cacaa4eed0e4203") @PathVariable String id) {
        if (!StringUtils.isNotBlank(id)) {
            return new ResDto(Const.PARAM_ERROR, "实验室id不为空");
        }
        ResDto resDto = iLaboratoryService.deleteLaboratoryById(request, id);
        return resDto;
    }


    @ApiOperation(httpMethod = "DELETE", value = "批量删除实验室信息", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/batchdelete", name = "批量删除实验室信息", method = RequestMethod.DELETE)
    public ResDto deleteLaboratoryByIds(HttpServletRequest request, @ApiParam(name = "msg", value = "[\"54f8c268f02c4ebf9cacaa4eed0e4203\",<Br>\"99f8c268a158c4ebf9cacaa4eed0e4203\"]") @RequestParam(required = true) String msg) {
        if (!StringUtils.isNotBlank(msg)) {
            return new ResDto(Const.PARAM_ERROR, "实验室ids不为空");
        }
        List<String> idLists = JsonMapper.defaultMapper().fromJson(msg, JsonMapper.defaultMapper().buildCollectionType(List.class, String.class));
        ResDto resDto = iLaboratoryService.deleteLaboratoryByIds(request, idLists);
        return resDto;
    }

    /**
     * Excel(实验室列表导出到Excel)
     *
     * @param msg
     * @param response
     */
    @ApiOperation(value = "Excel(按条件把实验室列表导出到Excel)", httpMethod = "GET")
    @RequestMapping(value = "/export", name = "Excel(按条件把实验室列表导出到Excel)", method = RequestMethod.GET)
    public ResDto laboratoryExport(HttpServletRequest request,@ApiParam(name = "msg", value = "{\"condition\":{<Br>\"lab_name\":\"XXXX\",\"unit_id\":\"afe34adf3\",\"building_id\":\"afe34adf3\",\"status\":\"0\"}}", required = true) @RequestParam(required = true) String msg, HttpServletResponse response) {
        try {
            FrontPage frontPage = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
            //salesReportService.performanceExport(frontPage, response, SalesCommon.SALES_ROLE_INSIDE);
            ResDto resDto = iLaboratoryService.laboratoryExport(frontPage, response,request);
            return resDto;
        } catch (Exception e) {
            //logger.error("导出销售业绩列表异常，异常信息:{}", e.getMessage());
            e.printStackTrace();
            return new ResDto(Const.PARAM_ERROR, "导出实验室列表异常!!");
        }
    }

    @Autowired
    private Validator globalValidator;

    /**
     * Excel表导入实验室表
     *
     * @param msg
     * @param request
     * @return
     */
    @ApiOperation(value = "Excel表导入实验室表", notes = "上传文件的id")
    @RequestMapping(value = "/import", name = "Excel表导入实验室表", method = RequestMethod.POST)
    public ResDto importCompanyPayment(@RequestParam(required = true) @ApiParam(name = "msg", value = "{\"id\":\"aaaa\"}") String msg, HttpServletRequest request) {
        try {
            LabImportExcelDto labImportExcelDto = JsonMapper.defaultMapper().fromJson(msg, LabImportExcelDto.class);
            if (labImportExcelDto == null) {
                log.error("导入实验室Excel文件参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "导入实验室Excel文件参数为空或有不正确的数据格式");
            }
            Set<ConstraintViolation<LabImportExcelDto>> constraintViolations = globalValidator.validate(labImportExcelDto);
            if (null != constraintViolations && !constraintViolations.isEmpty()) {
                StringBuffer buffer = new StringBuffer(64);
                for (ConstraintViolation<LabImportExcelDto> apiViolation : constraintViolations) {
                    buffer.append(apiViolation.getMessage());
                }
                log.info("必传参数 :{}", buffer.toString());
                ResDto resDto = new ResDto();
                resDto.setStatus(Const.PARAM_ERROR);
                resDto.setMsg(buffer.toString());
                return resDto;
            }
            return iLaboratoryService.labImportExcel(labImportExcelDto, request);
        } catch (Exception e) {
            log.error("导入公司发放文件，错误为：{}", e.getMessage());
            return new ResDto(ConstEum.SERVER_ERROR);
        }
    }

    /**
     * 要求：1.如果即配置院系又配置实验室，以配置实验室所在院系列表为准;
     * 2.如只配置院系，则显示该院系下所有的实验室所在院系列表为准;
     * 3.如只配置实验室，则显示该实验室所在院系列表为准;
     * 配置院系的列表+配置实验室所在的院系列表-(重复的院系列表)
     */
    @ApiOperation(httpMethod = "GET", value = "获取用户负责实验室所在院系列表+用户负责的院系列表", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/unit_list", name = "获取用户负责实验室所在院系列表+用户负责的院系列表", method = RequestMethod.GET)
    public ResDto getLaboratoryUnitFrontPage(HttpServletRequest request) {

        ResDto reDto = iLaboratoryService.getManagerUnitList(request);
        return reDto;


    }

    /**
     * 要求：1.如果即配置院系又配置实验室，以配置实验室所在的楼宇列表为准;
     * 2.如只配置院系，则显示该院系下所有的实验室所在的楼宇列表;
     * 3.如只配置实验室，则显示该实验室所在的楼宇列表;
     * 配置院系的列表+配置实验室所在的院系列表-(重复的院系列表)
     */
    @ApiOperation(httpMethod = "GET", value = "获取用户负责实验室所在楼宇+院系所在楼宇列表", consumes = MediaTypes.JSON)
    @RequestMapping(value = "/building_list", name = "获取用户负责实验室所在楼宇+院系所在楼宇列表", method = RequestMethod.GET)
    public ResDto getLaboratoryBuildingFrontPage(HttpServletRequest request) {

        ResDto reDto = iLaboratoryService.getManagerBuildingList(request);
        return reDto;


    }


}
